<template>
  <div class="home-container">
    <div class="header-row">
      <el-text size="large">网盘管理系统数据看板</el-text>
    </div>

    <!-- 欢迎栏 -->
    <div class="welcome-row">
      <el-card shadow="hover">
        <div class="welcome-card">
          <div style="display: flex; flex-direction: row;">
            <el-avatar class="avatar" style="margin-right: 20px;" :src="store.userInfo?.avatar" />
            <div>
              <el-text class="welcome-sentence">{{ welcomeSentence }}</el-text>
              <el-text type="info" size="small" truncated>{{ welcomeInfo }}</el-text>
            </div>
          </div>
          <el-text class="welcome-clock">{{ welcomeTime }}</el-text>
        </div>
      </el-card>
    </div>

    <!-- 概览卡片 -->
    <div class="overview-cards">
      <el-card shadow="hover" v-for="i in overviewList" :key="i.key">
        <div class="metric-content">
          <div class="metric-info">
            <div class="metric-title">{{ i.title }}</div>
            <div class="metric-value">{{ i.total }}</div>
            <div class="metric-change">
              今日增加 <span class="trend">↑ {{ i.today }}</span>
            </div>
          </div>
          <div class="metric-icon">
            <el-icon>
              <component :is="i.icon" />
            </el-icon>
          </div>
        </div>
      </el-card>
    </div>

    <div class="chart-row">
      <!-- 用户活跃度 -->
      <el-card shadow="hover" class="metric-card">
        <template #header>
          <div class="chart-header">
            <h3>用户活跃度</h3>
            <el-tag>近7天</el-tag>
          </div>
        </template>
        <v-chart class="chart" :option="recentOption" autoresize/>
      </el-card>

      <!-- 文件统计 -->
      <el-card shadow="hover" class="metric-card">
        <template #header>
          <div class="chart-header">
            <h3>文件类型</h3>
            <el-tag type="success">总量</el-tag>
          </div>
        </template>
        <v-chart class="chart" :option="propertyOption" autoresize />
      </el-card>
    </div>

    <div class="chart-row">
      <!-- 系统性能 -->
      <el-card shadow="hover" class="metric-card">
        <template #header>
          <div class="chart-header">
            <h3>系统性能指标</h3>
            <el-tag type="warning">最近24小时</el-tag>
          </div>
        </template>
        <v-chart class="chart" :option="systemOption" autoresize />
      </el-card>

      <el-card shadow="hover" class="metric-card">
        <template #header>
          <div class="chart-header">
            <h3>后台设置</h3>
            <el-tag type="success">配置</el-tag>
          </div>
        </template>
        <el-form label-width="auto">
          <el-form-item label="默认容量">
            <el-input v-model="config.defaultUserSpace">
              <template #append>MB</template>
            </el-input>
          </el-form-item>
          <el-form-item label="上传大小限制">
            <el-input v-model="config.uploadSizeLimit">
              <template #append>MB</template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <div style="display: flex; justify-content: center;width: 100%;">
              <el-button @click="loadConfig">重置</el-button>
              <el-button type="primary" @click="handleUplaodConfig">更新</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 底部表格 -->
    <div class="table-row">
      <el-card shadow="hover" class="metric-card">
        <template #header>
          <div class="table-header">
            <h3>活跃用户</h3>
            <el-button link size="small" @click="handleCheckAll">查看全部</el-button>
          </div>
        </template>
        <el-table v-loading="loading" :data="tableData" ref="multipleTableRef" row-key="id">
          <!-- 用户头像 -->
          <el-table-column prop="avatar" sortable label="头像">
            <template #default="{ row }">
              <el-avatar shape="square" :src="row.avatar" />
            </template>
          </el-table-column>
          <!-- 用户名 -->
          <el-table-column prop="username" label="用户名">
            <template #default="{ row }">
              <span>{{ row.username }}</span>
            </template>
          </el-table-column>
          <!-- 用户ID -->
          <el-table-column prop="id" label="用户ID">
            <template #default="{ row }">
              <span>{{ row.id }}</span>
            </template>
          </el-table-column>

          <!-- 创建时间 -->
          <el-table-column prop="createdAt" label="创建时间">
            <template #default="{ row }">
              <span>{{ formatToDateTime(row.createdAt) }}</span>
            </template>
          </el-table-column>
          <!-- 最后登录时间 -->
          <el-table-column prop="lastLoginTime" label="最后登录时间">
            <template #default="{ row }">
              <span>{{ formatToDateTime(row.lastLogin) }}</span>
            </template>
          </el-table-column>
          <!-- 最后登录IP -->
          <el-table-column prop="ip" label="最后登录IP">
            <template #default="{ row }">
              <ElTag>{{ row.ip }}</ElTag>
            </template>
          </el-table-column>
          <!-- 角色 -->
          <el-table-column prop="role" label="角色">
            <template #default="{ row }">
              <ElTag>{{ row.role }}</ElTag>
            </template>
          </el-table-column>
          <!-- 状态 -->
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <ElTag>{{ row.status }}</ElTag>
            </template>
          </el-table-column>
          <!-- 总空间 -->
          <el-table-column prop="storage" label="总空间">
            <template #default="{ row }">
              <ElTag>{{ formatFileSize(row.storage) }}</ElTag>
            </template>
          </el-table-column>

          <!-- 已用空间 -->
          <el-table-column prop="used" label="已用空间">
            <template #default="{ row }">
              <ElTag>{{ formatFileSize(row.used) }}</ElTag>
            </template>
          </el-table-column>

          <!-- 操作选项 -->
          <el-table-column prop="action" label="操作" min-width="200">
            <template #default="{ row }">
              <div style="display: flex;">
                <el-button link @click="handleUpdateSpace(row)">容量</el-button>

                <el-dropdown>
                  <el-button link type="primary">状态</el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleUpdateStatus(row, 'ACTIVE')">活跃</el-dropdown-item>
                      <el-dropdown-item @click="handleUpdateStatus(row, 'SUSPENDED')">冻结</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>

                <el-dropdown>
                  <el-button link type="success">角色</el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleUpdateRole(row, 'ADMIN')">管理员</el-dropdown-item>
                      <el-dropdown-item @click="handleUpdateRole(row, 'USER')">用户</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>

  <el-dialog v-model="dialogVisible" width="300" title="请输入新的空间大小">
    <el-input v-model="newSpaceSize" type="number">
      <template #append>MB</template>
    </el-input>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmUpdateSpace">
          确认修改
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, markRaw } from "vue";
import {
  getUsersApi,
  getOverviewApi,
  getRecentDaysApi,
  getPropertyApi,
  getLogsApi,
  getTenUsersApi,
  updateSpaceApi,
  updateStatusApi,
  updateRoleApi,
  getConfigApi,
  updateConfigApi
} from "../api";
import { formatToDateTime, formatFileSize } from "../utils/FormatUtil";
import { ElMessage, ElTag, ElMessageBox } from "element-plus";
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import {
  Folder,
  User,
  Document,
  Link
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { useStore } from "../stores";
import axios from "axios";

const store = useStore();

use([
  CanvasRenderer,
  BarChart,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const multipleTableRef = ref(null);
const tableData = ref([]); //表格数据
const loading = ref(false);
const dialogVisible = ref(null)
const newSpaceSize = ref(0)

const overviewList = ref([])

const currentRow = ref(null)

const loadData = async () => {
  loading.value = true;
  try {
    const res = await getTenUsersApi();
    tableData.value = res.map((item) => {
      return { ...item, avatar: `${import.meta.env.VITE_BASE_URL}api/user/avatar/${item.id}` };
    });
    console.log(tableData.value);
  } catch (error) {
    tableData.value = [];
    console.error("获取用户列表失败:", error);
    throw error;
  } finally {
    loading.value = false;
  }
};

const loadAllData = async () => {
  loading.value = true;
  try {
    const res = await getUsersApi();
    tableData.value = res.map((item) => {
      return { ...item, avatar: `${import.meta.env.VITE_BASE_URL}api/user/avatar/${item.id}` };
    });
    console.log(tableData.value);
  } catch (error) {
    tableData.value = [];
    console.error("获取用户列表失败:", error);
    throw error;
  } finally {
    loading.value = false;
  }
};

const loadOverview = async () => {
  try {
    const res = await getOverviewApi();
    console.log('数据概览',res);
    overviewList.value = [
      {
        key: 'user',
        title: '用户总数',
        total: res.user.total,
        today: res.user.today,
        icon: markRaw(User),
      },
      {
        key: 'file',
        title: '文件总数',
        total: res.file.total,
        today: res.file.today,
        icon: markRaw(Document),
      },
      {
        key: 'download',
        title: '下载总数',
        total: res.download.total,
        today: res.download.today,
        icon: markRaw(Folder),
      },
      {
        key: 'share',
        title: '分享总数',
        total: res.share.total,
        today: res.share.today,
        icon: markRaw(Link),
      },
    ]
  } catch (err) {
    console.error(err)
  }
}

const loadRecent = async () => {
  try {
    const data = await getRecentDaysApi();
    console.log('今日数据', data)
    recentOption.value = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999'
          }
        }
      },
      legend: {
        data: ['注册用户', '文件上传', '下载次数', '分享次数']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.user.map(item => item.date), // 使用用户数据的日期作为x轴
        axisPointer: {
          type: 'shadow'
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '人数',
          position: 'left',
          axisLabel: {
            formatter: '{value}人'
          },
          max: Math.max(...data.user.map(item => item.total)) * 2
        },
        {
          type: 'value',
          name: '次数',
          position: 'right',
          axisLabel: {
            formatter: '{value}次'
          },
          max: Math.max(...data.file.map(item => item.count), ...data.download.map(item => item.count), ...data.share.map(item => item.count)) * 2
        }
      ],
      series: [
        {
          name: '注册用户',
          type: 'bar',
          data: data.user.map(item => item.total),

        },
        {
          name: '文件上传',
          type: 'line',
          yAxisIndex: 1,
          data: data.file.map(item => item.count),
          symbol: 'circle',
        },
        {
          name: '下载次数',
          type: 'line',
          yAxisIndex: 1,
          data: data.download.map(item => item.count),
          symbol: 'diamond',
        },
        {
          name: '分享次数',
          type: 'line',
          yAxisIndex: 1,
          data: data.share.map(item => item.count),
          symbol: 'triangle',
        }
      ]
    };

  } catch (err) {
    console.error(err)
  }
}
const timer = ref(null);

onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
const loadWelcome = async () => {
  const predefinedWelcomeSentences = [
    '凌晨了，{username}，要注意休息哦。',
    '早上好，{username}，今天又是活力满满的一天！',
    '上午好，{username}，祝你有一个愉快的一天！',
    '中午好，{username}，要注意休息哦。',
    '下午好，{username}, 你一定有些累了，喝杯咖啡休息一下吧。',
    '晚上好，{username}, 莫道桑榆晚 为霞尚满天。',
    '深夜了，{username}, 夜深人静写代码是一种什么样的体验呢。',
  ]

  const time = dayjs().hour()
  let index = 0
  if (time < 6) {
    index = 0
  } else if (time < 9) {
    index = 1
  } else if (time < 11) {
    index = 2
  } else if (time < 13) {
    index = 3
  } else if (time < 18) {
    index = 4
  } else if (time < 22) {
    index = 5
  } else {
    index = 6
  }
  welcomeSentence.value = predefinedWelcomeSentences[index].replace('{username}', store.userInfo?.username);

  const respnse = await axios.get('https://v.api.aa1.cn/api/yiyan/index.php')
  console.log('每日一句',respnse.data)
  welcomeInfo.value = respnse.data.replace('<p>', '').replace('</p>', '')
  welcomeTime.value = dayjs().format('HH:mm:ss')
  timer.value = setInterval(() => {
    welcomeTime.value = dayjs().format('HH:mm:ss')
  }, 1000)
}

const loadProporty = async () => {
  try {
    const res = await getPropertyApi();
    console.log('文件比例', res)
    //1.视频 2.图片 3.音频 4.文档 5：其他
    let data = [
      { value: 0, name: '视频' },
      { value: 0, name: '图片' },
      { value: 0, name: '音频' },
      { value: 0, name: '文档' },
      { value: 0, name: '其他' },
    ]
    res.forEach(item => {
      data[item.name - 1].value = (item.value / 1024 / 1024).toFixed(2)
    })
    console.log(data)
    propertyOption.value = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}MB ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: ['视频', '图片', '音频', '文档', '其他']
      },
      series: [
        {
          name: '文件类型',
          type: 'pie',
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: data
        }
      ]
    }
  } catch (err) {
    console.error('获取文件比例失败', err)
  }
}

const loadLogs = async () => {
  try {
    const res = await getLogsApi();
    console.log('日志', res)
    systemOption.value = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999'
          }
        }
      },
      legend: {
        data: ['API请求量', '平均响应时间', '错误率']
      },
      grid: {
        left: '3%',
        right: '12%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: res.map(item => `${item.hour}点`),
      },
      yAxis: [
        {
          type: 'value',
          name: 'API请求量',
          min: 0,
          max: 1000,
          interval: 200,
          axisLabel: {
            formatter: '{value}次'
          }
        },
        {
          type: 'value',
          name: '平均响应时间',
          min: 0,
          max: 460,
          interval: 100,
          axisLabel: {
            formatter: '{value}ms'
          }
        },
        {
          type: 'value',
          name: '错误率',
          offset: 80,
          min: 0,
          max: 10,
          interval: 1,
          axisLabel: {
            formatter: '{value}%'
          }
        }
      ],
      series: [
        {
          name: 'API请求量',
          type: 'bar',
          data: res.map(item => item.count)
        },
        {
          name: '平均响应时间',
          type: 'line',
          yAxisIndex: 1,
          data: res.map(item => item.avgDuration)
        },
        {
          name: '错误率',
          type: 'line',
          yAxisIndex: 2,
          data: res.map(item => item.errorRate)
        }
      ]
    };
  } catch (err) {
    console.error(err)
  }
}


const loadConfig = async () => {
  try{
    const res = await getConfigApi();
    console.log('配置', res)
    config.value = res
  }catch(err){
    console.error(err)
  }
}

const welcomeSentence = ref('')
const welcomeInfo = ref('')
const welcomeTime = ref(dayjs().format('HH:mm:ss'))
// 存储使用情况图表配置
const propertyOption = ref(null)
// 用户活跃度图表配置
const recentOption = ref(null)
// 系统性能图表配置
const systemOption = ref(null)
const config = ref({
  defaultUserSpace: 0,
  uploadSizeLimit: 0,
})

const handleUpdateSpace = (row) => {
  currentRow.value = row
  newSpaceSize.value = row.storage / 1024 / 1024
  dialogVisible.value = true
}

const handleConfirmUpdateSpace = async () => {
  try {
    if(!currentRow.value || !newSpaceSize.value || newSpaceSize.value < 0 || newSpaceSize.value == currentRow.value.storage / 1024 / 1024) return
    await updateSpaceApi(currentRow.value.id,newSpaceSize.value * 1024 * 1024)
  } catch (err) {
    console.error(err)
  }finally{
    dialogVisible.value = false
    await loadData();
  }
}

const handleUpdateStatus = async (row, status) => {
  if(row.username == 'admin') {
    ElMessage.warning('不能修改管理员的状态');
    return
  }
  ElMessageBox.confirm(
    `你确定要修改用户的状态为${status}吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        await updateStatusApi(row.id, status)
      } catch (err) {
        console.error(err)
      }finally{
        await loadData();
      }
    })
}

const handleUpdateRole = async (row, role) => {
  if(row.username == 'admin') {
    ElMessage.warning('不能修改管理员的角色');
    return
  }
  ElMessageBox.confirm(
    `你确定要修改用户的角色为${role}吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        await updateRoleApi(row.id, role)
      } catch (err) {
        console.error(err)
      }finally{
        await loadData();
      }
    })
}


const handleCheckAll = () => {
  if(tableData.value.length < 10){
    ElMessage.warning('没有更多用户');
  }else{
    loadAllData()
  }
};

const handleUplaodConfig = async () => {
  try {
    await updateConfigApi(config.value)
  } catch (err) {
    console.error(err)
  }finally{
    await loadConfig();
  }
}


onMounted(async () => {
  await loadWelcome();
  await loadOverview();
  await loadRecent();
  await loadProporty();
  await loadLogs();
  await loadConfig();
  await loadData();
});
</script>

<style scoped>
.header-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.welcome-row {
  display: grid;
  gap: 16px;
  margin-bottom: 20px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.chart-row {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.welcome-card {
  display: flex;
  align-items: center;
  justify-content: space-around
}

.welcome-sentence {
  display: flex;
}

.welcome-clock {
  text-align: center;
  font-size: xx-large;
  font-weight: bold;
  font-family: "Orbitron", sans-serif;
}

.metric-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.metric-info {
  flex: 1;
}

.metric-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.metric-value .unit {
  font-size: 16px;
  font-weight: normal;
}

.metric-change {
  font-size: 12px;
  color: #909399;
}

.trend {
  font-weight: bold;
  color: #67c23a;
}

.metric-icon {
  font-size: 40px;
  color: #409eff;
  opacity: 0.8;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  height: 350px;
  width: 100%;
}

.table-row {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

@media (max-width: 1200px) {
  .overview-cards {
    grid-template-columns: repeat(2, 1fr);
  }

  .chart-row {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {

  .welcome-card {
    flex-direction: column;
  }

  .overview-cards {
    grid-template-columns: 1fr;
  }

  .dashboard-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .time-selector {
    width: 100%;
    flex-direction: column;
  }


}
</style>